package com.itheima.edu.info.manager.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Period;
import java.time.format.DateTimeFormatter;
import java.util.Date;

public final class DateUtil {
    /**
     * Don't let anyone instantiate this class.
     */
    private DateUtil(){}

    /*
        通过生日计算年龄
     */
    public static int getAgeByBirthday(String birthday){    // "1999-11-11"
        try {
            //1. 创建SimpleDateFormat 对象
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            //2. 将传入的生日字符串解析成对应的Date对象
            Date birDate = sdf.parse(birthday);
            //3. 获取当前系统时间
            Date now = new Date();
            //4. 计算两个日期间的差值
            long ageTime = now.getTime() - birDate.getTime();
            //5. 通过毫秒值计算年龄
            int age = (int) (ageTime / 1000L / 60 / 60 / 24 / 365);
            //6. 将计算出的年龄返回
            return age;
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return 0;
    }

    public static int getAgeByBirthday(String birthday,int abc){    // "1999-11-11"
        try {
            //1. 将birthday解析成一个LocalDateTime对象
            //birthday += " 00:00:00";
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            LocalDate birthTime = LocalDate.parse(birthday, formatter);

            //2. 拿到当前日期
            LocalDate now = LocalDate.now();

            //3. 计算两个日期的差值
            Period period = Period.between(birthTime, now);

            return period.getYears();

        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }
}
